<script setup lang="ts">
import { reactive, ref, onMounted, watch } from "vue";
import type { FormInstance } from "element-plus";
import { addUser, updateUser } from "@/api";
import { ElMessage } from "element-plus";
const props = defineProps(["isShow", "user"]);
const emit = defineEmits(["closeDialog"]);
const formObj = reactive({
  username: "",
  password: "",
});
const formRef = ref<FormInstance>();
const rules = reactive({
  username: [{ required: true, message: "用户名称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }],
});
async function submitForm() {
  await formRef.value?.validate(async (valid, _fields) => {
    if (valid) {
      var res = null;
      if (props.user.id == 0) {
        const data = {
          username: formObj.username,
          password: formObj.password,
          salt: "",
          avatar: "",
          state: false,
        };
        res = await addUser(data);
      } else {
        const data = {
          id: props.user.id,
          username: formObj.username,
          password: formObj.password,
          salt: props.user.salt,
          avatar: props.user.avatar,
          state: props.user.state,
        };
        res = await updateUser(data);
      }

      if (res.data.errno == 0) {
        emit("closeDialog");
        ElMessage.success(res.data.errmsg);
      } else {
        ElMessage.error(res.data.errmsg);
      }
    }
  });
}
function initForm() {
  if (props.user.id != 0) {
    formObj.username = props.user.username;
    formObj.password = "";
  } else {
    formObj.username = "";
    formObj.password = "";
  }
}
watch(props, () => {
  initForm();
});
onMounted(() => {
  initForm();
});
</script>

<template>
  <el-form
    ref="formRef"
    :model="formObj"
    :rules="rules"
    label-width="120"
    status-icon
  >
    <el-form-item label="用户名称" prop="username">
      <el-input
        v-model="formObj.username"
        style="width: 400px"
        placeholder="请填写用户名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="用户密码" prop="password">
      <el-input
        v-model="formObj.password"
        style="width: 400px"
        placeholder="请填写用户密码"
        type="password"
      ></el-input>
    </el-form-item>
    <el-form-item label="">
      <el-button type="primary" @click="submitForm">{{
        props.user.id == 0 ? "新增" : "修改"
      }}</el-button>
      <el-button @click="initForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
